package com.hidtechs.popfax.controller;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.net.ssl.HttpsURLConnection;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.hidtechs.popfax.xml.XMLLoginHandler;

public class Requestor {

	
	
	public ArrayList<Object> requestData(final HashMap<String,String> attributes , HttpURLConnection conn) {

		try{
			System.out.println(attributes);
			
			DataOutputStream dataOutputStream=new DataOutputStream(conn.getOutputStream());

			Set keys=attributes.keySet();
			Iterator iter= keys.iterator();
			String content="";
			for(int m=0;iter.hasNext();m++){
				Object key=iter.next();
				if(m!=0)
				{
					content +="&";
				}
				content +=key+"="+URLEncoder.encode(attributes.get(key),"UTF-8");
			}

			System.out.println(content);
			dataOutputStream.writeBytes(content);
			dataOutputStream.flush();
			dataOutputStream.close();
			System.out.println("Response Msg="+conn.getResponseMessage());
		
			return XMLImplementer(conn.getInputStream());

		}catch(Exception e){
			System.out.println(e.getMessage());
			e.printStackTrace();
			return null;
		}
	}

	public ArrayList<Object> XMLImplementer(InputStream dataStreamFromServer)
	{
		try{
			
			/* Get a SAXParser from the SAXPArserFactory. */ 
			SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); 
			SAXParser saxParser = saxParserFactory.newSAXParser(); 
	
			/* Get the XMLReader of the SAXParser we created. */ 
			XMLReader xmlReader = saxParser.getXMLReader(); 
			/* Create a new ContentHandler and apply it to the XML-Reader*/ 
			XMLLoginHandler xLoginHandler = new XMLLoginHandler(); 
			xmlReader.setContentHandler(xLoginHandler); 
			
			System.out.println("XML Implementer="+dataStreamFromServer);
			/* Parse the xml-data from our URL. */ 
			System.out.println(xmlReader);
			xmlReader.parse(new InputSource(dataStreamFromServer));
			System.out.println("parsed");
			
			return xLoginHandler.arrayOfObject;
		} catch(Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
			return null;
		}
		
	}
	
	
	}

